import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import logging
import os
import pandas as pd
from pathlib import Path
import threading
from itertools import zip_longest
import sys
import subprocess

class ExportTab(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent, padding="10")
        
        # 初始化变量
        self.export_dir = None
        self.output_dir = None  # 输出图片文件夹路径
        self.export_thread = None
        self.is_exporting = False
        self.selected_folders = set()  # 存储选中的子文件夹
        self.folder_checkboxes = {}  # 存储子文件夹复选框
        
        # 创建UI组件
        self.create_export_frame()
        
    def create_export_frame(self):
        export_frame = ttk.LabelFrame(self, text="导出设置", padding="10")
        export_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), padx=5, pady=5)
        export_frame.columnconfigure(0, weight=1)
        export_frame.columnconfigure(1, weight=1)
        export_frame.columnconfigure(2, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)
        
        # 输出图片文件夹选择
        self.output_dir_var = tk.StringVar()
        ttk.Label(export_frame, text="选择根目录：").grid(row=0, column=0, padx=5, pady=5, sticky=(tk.W, tk.E))
        ttk.Entry(export_frame, textvariable=self.output_dir_var, width=40).grid(row=0, column=1, padx=5, pady=5, sticky=(tk.W, tk.E))
        ttk.Button(export_frame, text="选择文件夹", command=self.select_output_directory).grid(row=0, column=2, padx=5, pady=5, sticky=(tk.W, tk.E))
        
        # 子文件夹选择区域
        self.folders_frame = ttk.LabelFrame(export_frame, text="选择要导出的子文件夹", padding="5")
        self.folders_frame.grid(row=1, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=5)
        self.folders_frame.columnconfigure(0, weight=1)
        self.folders_frame.columnconfigure(1, weight=1)
        self.folders_frame.columnconfigure(2, weight=1)
        
        # 导出目录选择
        self.dir_path_var = tk.StringVar()
        ttk.Label(export_frame, text="导出目录：").grid(row=2, column=0, padx=5, pady=5, sticky=(tk.W, tk.E))
        ttk.Entry(export_frame, textvariable=self.dir_path_var, width=40).grid(row=2, column=1, padx=5, pady=5, sticky=(tk.W, tk.E))
        ttk.Button(export_frame, text="选择目录", command=self.select_export_directory).grid(row=2, column=2, padx=5, pady=5, sticky=(tk.W, tk.E))
        
        # 导出格式选择
        ttk.Label(export_frame, text="导出格式：").grid(row=3, column=0, padx=5, pady=5, sticky=(tk.W, tk.E))
        self.export_format = ttk.Combobox(export_frame, values=["Excel", "CSV"], state="readonly")
        self.export_format.set("Excel")
        self.export_format.grid(row=3, column=1, padx=5, pady=5, sticky=(tk.W, tk.E))
        
        # # 导出选项
        # options_frame = ttk.LabelFrame(export_frame, text="导出选项", padding="5")
        # options_frame.grid(row=4, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=10)
        
        # self.include_images = tk.BooleanVar(value=True)
        # ttk.Checkbutton(options_frame, text="包含图片", variable=self.include_images).grid(row=0, column=0, padx=5)
        
        # self.include_timestamp = tk.BooleanVar(value=True)
        # ttk.Checkbutton(options_frame, text="包含时间戳", variable=self.include_timestamp).grid(row=0, column=1, padx=5)
        
        # 导出按钮和进度条
        button_frame = ttk.Frame(export_frame)
        button_frame.grid(row=4, column=0, columnspan=3, pady=10, sticky=(tk.W, tk.E))
        button_frame.columnconfigure(0, weight=1)
        button_frame.columnconfigure(1, weight=1)
        
        ttk.Button(button_frame, text="开始导出", command=self.start_export).grid(row=0, column=0, padx=5, sticky=(tk.W, tk.E))
        ttk.Button(button_frame, text="取消导出", command=self.cancel_export).grid(row=0, column=1, padx=5, sticky=(tk.W, tk.E))
        
        # 进度条
        self.export_progress = ttk.Progressbar(export_frame, mode='determinate')
        self.export_progress.grid(row=5, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=5)
        
        # 状态标签
        self.status_label = ttk.Label(export_frame, text="就绪")
        self.status_label.grid(row=6, column=0, columnspan=3, pady=5, sticky=(tk.W, tk.E))

    def select_output_directory(self):
        dir_path = filedialog.askdirectory()
        if dir_path:
            self.output_dir = dir_path
            self.output_dir_var.set(dir_path)
            self.update_folder_checkboxes()
            logging.info(f"选择根目录: {dir_path}")

    def update_folder_checkboxes(self):
        # 清除现有的复选框
        for widget in self.folders_frame.winfo_children():
            widget.destroy()
        self.folder_checkboxes.clear()
        self.selected_folders.clear()
        
        if not self.output_dir:
            return
            
        # 获取所有子文件夹
        subfolders = [f.name for f in os.scandir(self.output_dir) if f.is_dir()]
        
        # 创建复选框
        for i, folder in enumerate(sorted(subfolders)):
            var = tk.BooleanVar(value=True)  # 默认选中
            cb = ttk.Checkbutton(self.folders_frame, text=folder, variable=var,
                                command=lambda f=folder, v=var: self.on_folder_selection(f, v))
            cb.grid(row=i//3, column=i%3, padx=5, pady=2, sticky=tk.W)
            self.folder_checkboxes[folder] = var
            self.selected_folders.add(folder)

    def on_folder_selection(self, folder, var):
        if var.get():
            self.selected_folders.add(folder)
        else:
            self.selected_folders.discard(folder)

    def select_export_directory(self):
        dir_path = filedialog.askdirectory()
        if dir_path:
            self.export_dir = dir_path
            self.dir_path_var.set(dir_path)
            logging.info(f"选择导出目录: {dir_path}")

    def get_folder_structure(self):
        """获取选中的子文件夹结构和文件名"""
        if not self.output_dir or not self.selected_folders:
            return None, None
        
        # 获取所有文件名
        all_files = []
        for root, dirs, files in os.walk(self.output_dir):
            rel_path = os.path.relpath(root, self.output_dir)
            if rel_path == '.' or rel_path in self.selected_folders:
                for file in files:
                    all_files.append(os.path.relpath(os.path.join(root, file), self.output_dir))
        
        return list(self.selected_folders), all_files

    def show_export_success_dialog(self, file_path):
        dialog = tk.Toplevel(self)
        dialog.title("导出成功")
        dialog.geometry("320x120")
        dialog.grab_set()
        ttk.Label(dialog, text="数据导出成功！").pack(pady=15)
        btn_frame = ttk.Frame(dialog)
        btn_frame.pack(pady=5, fill=tk.X, expand=True)
        def close():
            dialog.destroy()
        def open_folder():
            folder = os.path.dirname(file_path)
            if sys.platform.startswith('darwin'):
                subprocess.Popen(['open', folder])
            elif sys.platform.startswith('win'):
                os.startfile(folder)
            elif sys.platform.startswith('linux'):
                subprocess.Popen(['xdg-open', folder])
            dialog.destroy()
        ttk.Button(btn_frame, text="确认", command=close).pack(side=tk.LEFT, padx=20, expand=True, fill=tk.X)
        ttk.Button(btn_frame, text="打开文件位置", command=open_folder).pack(side=tk.RIGHT, padx=20, expand=True, fill=tk.X)

    def export_data(self):
        """导出数据到Excel或CSV"""
        try:
            # 表头顺序与复选框顺序一致
            subfolders = [folder for folder in self.folder_checkboxes if self.folder_checkboxes[folder].get()]
            if not subfolders:
                self.status_label.config(text="没有找到可导出的数据")
                return

            # 获取每个子文件夹下的文件名（无后缀，排序）
            folder_files = []
            for folder in subfolders:
                folder_path = os.path.join(self.output_dir, folder)
                if os.path.isdir(folder_path):
                    files = [os.path.splitext(f)[0] for f in sorted(os.listdir(folder_path)) if os.path.isfile(os.path.join(folder_path, f))]
                    folder_files.append(files)
                else:
                    folder_files.append([])

            # 用zip_longest对齐
            rows = list(zip_longest(*folder_files, fillvalue=""))

            # 创建DataFrame
            df = pd.DataFrame(rows, columns=subfolders)

            # 导出文件（不带index）
            export_path = os.path.join(self.export_dir, f"导出结果_{pd.Timestamp.now().strftime('%Y%m%d_%H%M%S')}")
            if self.export_format.get() == "Excel":
                file_path = f"{export_path}.xlsx"
                df.to_excel(file_path, index=False)
            else:
                file_path = f"{export_path}.csv"
                df.to_csv(file_path, index=False)

            self.status_label.config(text="导出完成")
            self.show_export_success_dialog(file_path)
            
        except Exception as e:
            logging.error(f"导出失败: {str(e)}")
            self.status_label.config(text=f"导出失败: {str(e)}")
            messagebox.showerror("错误", f"导出失败: {str(e)}")
        finally:
            self.is_exporting = False
            self.export_progress['value'] = 0

    def start_export(self):
        if not self.output_dir:
            messagebox.showwarning("警告", "请先选择输出图片文件夹")
            return
        if not self.export_dir:
            messagebox.showwarning("警告", "请先选择导出目录")
            return
            
        if self.is_exporting:
            messagebox.showwarning("警告", "正在导出中，请等待...")
            return
            
        self.is_exporting = True
        self.status_label.config(text="正在导出...")
        self.export_progress['value'] = 0
        
        # 在新线程中执行导出
        self.export_thread = threading.Thread(target=self.export_data)
        self.export_thread.daemon = True
        self.export_thread.start()
        
    def cancel_export(self):
        if not self.is_exporting:
            return
            
        self.is_exporting = False
        self.status_label.config(text="导出已取消")
        self.export_progress['value'] = 0
        logging.info("取消导出") 